package com.shsoft.task;

import com.alibaba.fastjson.JSONObject;
import com.shsoft.component.BarComponent;
import com.shsoft.component.BaseComponent;
import com.shsoft.component.DataComponent;
import com.shsoft.config.PCStatusConstant;
import com.shsoft.controller.MainController;
import com.shsoft.entity.HardWareInfo;
import com.shsoft.entity.HefengQueryAirInfo;
import com.shsoft.entity.HefengQueryWeatherInfo;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.WritableImage;
import okhttp3.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

public class WeatherTask implements Runnable{

    private String key;

    private String cityID;

    private MainController controller;

    private ThreadPoolTaskExecutor taskExecutor;

    public WeatherTask(String key, String cityID, MainController controller, ThreadPoolTaskExecutor taskExecutor) {
        this.key = key;
        this.cityID = cityID;
        this.controller = controller;
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void run() {
        OkHttpClient client_nowWeather = new OkHttpClient();
        Request request_nowWeather = new Request.Builder().url(PCStatusConstant.WEATHER_URL + key + "&location=" + cityID).build();
        client_nowWeather.newCall(request_nowWeather).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response){
                if (response.isSuccessful()){
                    try {
                        String s = new String(response.body().bytes(), "utf-8");
//                            System.out.println(s);
                        HefengQueryWeatherInfo info = JSONObject.parseObject(s, HefengQueryWeatherInfo.class);
                        String code = info.getCode();
                        if(code.equals("200")){
                            HardWareInfo.cityTemp = Integer.parseInt(info.getNow().getTemp());
                            HardWareInfo.cityHum = Integer.parseInt(info.getNow().getHumidity());
                            HardWareInfo.cityWeatherText = getWeaText(Integer.parseInt(info.getNow().getIcon()));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        OkHttpClient client_air = new OkHttpClient();
        Request request_air = new Request.Builder().url(PCStatusConstant.AIR_URL + key + "&location=" + cityID).build();
        client_air.newCall(request_air).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}
            @Override
            public void onResponse(Call call, Response response){
                if (response.isSuccessful()){
                    try {
                        String s = new String(response.body().bytes(), "utf-8");
                        HefengQueryAirInfo info = JSONObject.parseObject(s, HefengQueryAirInfo.class);
                        String code = info.getCode();
                        if(code.equals("200")) {
                            HardWareInfo.cityAqi = Integer.parseInt(info.getNow().getAqi());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        ArrayList<BaseComponent> componentList = controller.communicationComponentList;
        Map<String, WritableImage> componentBaseImageMap = controller.componentBaseImageMap;
        if(componentList.size() > 0 && componentBaseImageMap.size() > 0){
            for (BaseComponent component : componentList) {
                if(component.getType() == BaseComponent.ComponentType.BAR){
                    BarComponent barComponent = (BarComponent) component;
                    if(PCStatusConstant.weatherList.contains(barComponent.getName())){
                        Canvas canvas = new Canvas(barComponent.getTotalWidth(), barComponent.getTotalHeight());
                        GraphicsContext gc = canvas.getGraphicsContext2D();
                        gc.drawImage(componentBaseImageMap.get(PCStatusConstant.PRE_BAR_COMPONENT + barComponent.getName()), 0, 0);
                        barComponent.drawComponentToSmallCanvas(gc);
                        Platform.runLater(() -> {
                            BufferedImage image = SwingFXUtils.fromFXImage(canvas.snapshot(null, null), null);
                            taskExecutor.execute(new ProcessingImageDataTask(image, barComponent.getBorderX(), barComponent.getBorderY(), false));
                        });
                    }
                }
                if(component.getType() == BaseComponent.ComponentType.DATA){
                    DataComponent dataComponent = (DataComponent) component;
                    if(PCStatusConstant.weatherList.contains(dataComponent.getName())){
                        Canvas canvas = new Canvas(dataComponent.getBorderWidth(), dataComponent.getBorderHeight());
                        GraphicsContext gc = canvas.getGraphicsContext2D();
                        gc.drawImage(componentBaseImageMap.get(PCStatusConstant.PRE_DATA_COMPONENT + dataComponent.getName()), 0, 0);
                        dataComponent.drawComponentToSmallCanvas(gc);
                        Platform.runLater(() -> {
                            BufferedImage image = SwingFXUtils.fromFXImage(canvas.snapshot(null, null), null);
                            taskExecutor.execute(new ProcessingImageDataTask(image, dataComponent.getBorderX(), dataComponent.getBorderY(), false));
                        });
                    }
                }
            }
        }
    }

    private String getWeaText(int icon){
        String s = "";
        switch (icon){
            case 100:
            case 150:
                s = "晴";
                break;
            case 104:
                s = "阴";
                break;
            case 300:
            case 301:
            case 305:
            case 306:
            case 307:
            case 308:
            case 309:
            case 310:
            case 311:
            case 312:
            case 313:
            case 314:
            case 315:
            case 316:
            case 317:
            case 318:
            case 350:
            case 351:
            case 399:
                s = "雨";
                break;
            case 101:
            case 102:
            case 103:
            case 151:
            case 152:
            case 153:
                s = "云";
                break;
            case 304:
                s = "雹";
                break;
            case 500:
            case 501:
            case 502:
            case 509:
            case 510:
            case 511:
            case 512:
            case 513:
            case 514:
            case 515:
                s = "雾";
                break;
            case 503:
            case 504:
            case 507:
            case 508:
                s = "尘";
                break;
            case 302:
            case 303:
                s = "雷";
                break;
            case 400:
            case 401:
            case 402:
            case 403:
            case 404:
            case 405:
            case 406:
            case 407:
            case 408:
            case 409:
            case 410:
            case 456:
            case 457:
            case 499:
                s = "雪";
                break;
            default:
                s = "晴";
                break;
        }
        return s;
    }
}
